<?php

namespace App\Admin\Forms\User;

use App\Exceptions\AdminInvalidRequestException;
use App\Models\Account;
use App\Models\User;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class DeductionForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $money = $input['money'] * 100;
        $user_id = $this->payload['id'];
        DB::transaction(function () use ($user_id, $money) {
            $user = User::query()->where('id', '=', $user_id)->lockForUpdate()->first();
            if ($money > $user->balance) {
                throw new AdminInvalidRequestException('用户余额不足');
            }
            $user->where('id', $user->id)->decrement('balance', $money);
            $user->save();
            (new Account())->store($user->id, -$money, Account::SYSTEM_WITHDRAWAL);
        });
        return $this
            ->response()
            ->success(trans('admin.succeeded'))
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('money', '扣款金额')->rules('required|numeric|min:1');
    }

}
